package com.zhs.gccs.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.google.gson.Gson;
import com.liulishuo.okdownload.DownloadTask;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.trello.rxlifecycle2.components.support.RxAppCompatDialogFragment;
import com.zhs.gccs.base.App;
import com.zhs.gccs.base.BaseActivity;
import com.zhs.gccs.dialog.SimpleLoadDialog;
import com.zhs.gccs.http.ProgressObserver;
import com.zhs.gccs.utils.DialogUtils;
import com.zhs.gccs.utils.PermissionListener;
import com.zhs.gccs.utils.SharedPrefHelper;

import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.RequestBody;


public abstract class BaseFragment extends RxAppCompatDialogFragment {
    public final String TAG = "CAI_JI";
    public App app;
    protected Context context;
    protected View rootView;
    public float density;
    public BaseActivity baseActivity;
    private SimpleLoadDialog simpleLoadDialog;


    public void showDialog() {
        if (simpleLoadDialog != null) {
            simpleLoadDialog.show();
        } else {
            simpleLoadDialog = new SimpleLoadDialog(this.context, false);
            simpleLoadDialog.show();
        }
    }

    public void dismissDialog() {
        if (simpleLoadDialog != null) {
            simpleLoadDialog.dismiss();
            simpleLoadDialog = null;
        }
    }

    public BaseFragment() {

    }

    @Override
    public void onAttach(Context mContext) {
        super.onAttach(mContext);
        if (mContext != null) {
            this.context = mContext;
        } else {
            this.context = getActivity();
        }
        if (mContext != null) {
            density = mContext.getResources().getDisplayMetrics().density;
            baseActivity = (BaseActivity) getActivity();
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (app == null) {
            app = (App) (getActivity().getApplication());
        }
    }


    protected abstract int getLayout();

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(getLayout(), container, false);
            rootView.setBackgroundResource(android.R.color.transparent);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }

        ButterKnife.bind(this, rootView);
        return rootView;
    }

    public void requestPermission(Context context,
                                  PermissionListener permissionListener,
                                  String... permissions ) {
        PermissionUtils.permission(permissions)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(@NonNull UtilsTransActivity activity,
                                          @NonNull ShouldRequest shouldRequest) {
//                        shouldRequest.again(true);//强制权限申请
                        shouldRequest.again(true);
                    }
                }).callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {
                        if(permissionListener!=null) permissionListener.onSucceed();
                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever,
                                         List<String> permissionsDenied) {
                        if (!permissionsDeniedForever.isEmpty()||!permissionsDenied.isEmpty()) {
                            DialogUtils.showOpenAppSettingDialog(context);
                            return;
                        }
//                        requestPermission(context,permissionListener);
                        if(permissionListener!=null) permissionListener.onFailed();
                    }
                }).request();
    }

    public RequestBody createRequestBody(List<Map<String, Object>> list){
        return FormBody.create(new Gson().toJson(list),
                MediaType.parse("application/json; charset=utf-8"));
    }

    public RequestBody createRequestBody(Map<String, Object> paramMap){
        return FormBody.create(new Gson().toJson(paramMap),
                MediaType.parse("application/json; charset=utf-8"));
    }

    public void toSubscribeSingleOb(Observable<String> ob, ProgressObserver observer) {
        ob.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<String>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribe(observer);
    }

    public static DownloadTask createTasK(String url, String parentPath, String fileName) {
        DownloadTask.Builder builder = new DownloadTask.Builder(url, parentPath, fileName)
                .setFilenameFromResponse(false)//是否使用 response header or url path 作为文件名，此时会忽略指定的文件名，默认false
                .setPassIfAlreadyCompleted(true)//如果文件已经下载完成，再次下载时，是否忽略下载，默认为true(忽略)，设为false会从头下载
                .setConnectionCount(5)  //需要用几个线程来下载文件，默认根据文件大小确定；如果文件已经 split block，则设置后无效
                .setPreAllocateLength(false) //在获取资源长度后，设置是否需要为文件预分配长度，默认false
                .setMinIntervalMillisCallbackProcess(1500) //通知调用者的频率，避免anr，默认3000
                .setWifiRequired(false)//是否只允许wifi下载，默认为false
                .setAutoCallbackToUIThread(true) //是否在主线程通知调用者，默认为true
                //.setHeaderMapFields(new HashMap<String, List<String>>())//设置请求头
//                .addHeader(String key, String value)//追加请求头
                .setPriority(0)//设置优先级，默认值是0，值越大下载优先级越高
                .setReadBufferSize(4096)//设置读取缓存区大小，默认4096
                .setFlushBufferSize(16384)//设置写入缓存区大小，默认16384
                .setSyncBufferSize(65536)//写入到文件的缓冲区大小，默认65536
                .setSyncBufferIntervalMillis(1500);//写入文件的最小时间间隔，默认2000
        builder.addHeader("Authorization","Bearer " + SharedPrefHelper.getInstance().getToken());
        return builder.build();
    }
}
